/**
 * Created by ben on 4/27/16.
 */
var casper = require("casper").create({
  onRunComplete: function() {
    // Don't exit on complete.
  }
});
casper.options.waitTimeout = 1000;

var mouse = require("mouse").create(casper);
var system = require('system');
var wait_before_end = 1000;

port = system.args[4];

server = require('webserver').create();

service = server.listen(port, {
    'keepAlive': true
    }, function (request, response) {
    // phantom.clearCookies();

    if (request.method == 'GET') {
      response.statusCode = 403;
      response.write("method not allowed!");
      response.close();
      return;
    }

    var fetch = JSON.parse(request.postRaw);
    console.log('paramters:'+JSON.stringify(fetch, null, 2));

    casper.steps = [];
    casper.step = 0;

    var first_response = null,
        finished = false,
        start_time = Date.now(),
        end_time = null,
        script_executed = false,
        script_result = null;

    console.log('url:'+fetch.url);

    casper.open(fetch.url, {
        method: fetch.method,
        data: fetch.data
    });

    casper.then(function () {
        if (fetch.headers && fetch.headers['User-Agent']) {
            casper.page.settings.userAgent = fetch.headers['User-Agent'];
        }
        casper.page.settings.loadImages = fetch.load_images ? true : false;
        casper.page.settings.resourceTimeout = fetch.timeout ? fetch.timeout * 1000 : 120*1000;
        if (fetch.headers) {
            casper.page.customHeaders = fetch.headers;
        }
    });

    casper.then(function () {
       if (!script_executed && fetch.js_run_at == "document-start") {
           script_executed = true;
           console.log('running document-start script.');

           var label_name = fetch.label_name;
           label_name = '下一页';
           var label_type = fetch.label_type;
           console.log(fetch.js_run_at + '/label_name:' + label_name + ",label_type:" + label_type);

           if(label_name && label_name != '' && label_type && label_type != ''){
               this.clickLabel(label_name, label_type);
           }
           script_result = 'True';
      }
    });

    casper.then(function () {
       if (!script_executed && fetch.js_run_at != "document-start") {
           script_executed = true;
           console.log('running document-end script.');
           var label_name = fetch.label_name;
           label_name = '下一页';
           var label_type = fetch.label_type;
           console.log(fetch.js_run_at + '/label_name:' + label_name + ",label_type:" + label_type);
           if(label_name && label_name != '' && label_type && label_type != ''){
               this.clickLabel(label_name, label_type);
           }
           script_result = 'True';
       }
    });

    setTimeout(function(page) {
      if (first_response) {
        end_time = Date.now()-1;
        make_result(page);
      }
    }, casper.page.settings.resourceTimeout, casper.page);

    // casper.then(function () {
    //     finished = true;
    //     end_time = Date.now() + wait_before_end;
    //     console.log("waiting "+wait_before_end+"ms before finished.");
    //     console.log('content:'+ length(casper.page.content).toString());
    //     make_result(casper.page);
    // });

    casper.run(function _do() {
        finished = true;
        end_time = Date.now() + wait_before_end;
        console.log("waiting "+wait_before_end+"ms before finished.");
        console.log('content:'+ casper.page.content);
        make_result(casper.page);
    });

    // make response
    function make_result(page) {
      if (!end_time || finished) {
        return;
      }

      var result = {};
      try {
        result = _make_result(page);
      } catch (e) {
        result = {
          orig_url: fetch.url,
          status_code: 599,
          error: e.toString(),
          content:  '',
          headers: {},
          url: page.url,
          cookies: {},
          time: (Date.now() - start_time) / 1000,
          save: fetch.save
        }
      }

      console.log("["+result.status_code+"] "+result.orig_url+" "+result.time);

      var body = unescape(encodeURIComponent(JSON.stringify(result, null, 2)));
      response.statusCode = 200;
      response.headers = {
        'Cache': 'no-cache',
        'Content-Type': 'application/json',
        'Connection': 'Keep-Alive',
        'Keep-Alive': 'timeout=5, max=100',
        'Content-Length': body.length
      };
      response.setEncoding("binary");
      response.write(body);
      response.close();
      finished = true;
      page.close();
    }

    function _make_result(page) {
      var cookies = {};
      page.cookies.forEach(function(e) {
        cookies[e.name] = e.value;
      });

      var headers = {};
      if (first_response.headers) {
        first_response.headers.forEach(function(e) {
          headers[e.name] = e.value;
        });
      }

      return {
        orig_url: fetch.url,
        status_code: first_response.status || 599,
        error: first_response.errorString,
        content:  page.content,
        headers: headers,
        url: page.url,
        cookies: cookies,
        time: (Date.now() - start_time) / 1000,
        js_script_result: script_result,
        save: fetch.save
      }
    }

    response.write(casper.page.content);
    response.close();
});

if (service) {
    console.log('Web server running on port ' + port);
  } else {
    console.log('Error: Could not create web server listening on port ' + port);
    casper.close();
  }
